package com.niit.musicserve.controller;

import com.alibaba.fastjson.JSONObject;
import com.niit.musicserve.annotation.RequireRole;
import com.niit.musicserve.entity.Admin;
import com.niit.musicserve.service.AdminService;
import com.niit.musicserve.utils.Const;
import com.niit.musicserve.utils.JwtUtil;
import com.niit.musicserve.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;

@RestController
@RequestMapping("/admin")
public class AdminController {
	
	@Autowired
	private AdminService adminService;
	@Autowired
	private JwtUtil jwtUtil;
	
	/**
	 * 验证密码
	 */
	@RequestMapping(value = "/login/status", method = RequestMethod.POST)
	public Result<JSONObject> verifyPassword(
		HttpServletRequest request)
	{
		
		try{
			String adminName = request.getParameter("name");
			String adminPassword = request.getParameter("password");
			
			// 参数校验
			if (adminName == null || adminName.trim().isEmpty() ||
			    adminPassword == null || adminPassword.trim().isEmpty()) {
				
				// 读取请求体中的JSON数据
				StringBuilder sb = new StringBuilder();
				String line;
				try (BufferedReader reader = request.getReader()) {
					while ((line = reader.readLine()) != null) {
						sb.append(line);
					}
				}
				
				if (! sb.isEmpty()) {
					JSONObject jsonParams = JSONObject.parseObject(sb.toString());
					if (adminName == null || adminName.trim().isEmpty()) {
						adminName = jsonParams.getString("name");
					}
					if (adminPassword == null || adminPassword.trim().isEmpty()) {
						adminPassword = jsonParams.getString("password");
					}
				}
			}
			
			// 参数校验
			if (adminName == null || adminName.trim().isEmpty() ||
			    adminPassword == null || adminPassword.trim().isEmpty()) {
				return Result.error("用户名或密码不能为空");
			}
			
			boolean verifyResult = adminService.verifyPassword(
				adminName,
				adminPassword);
			if (verifyResult) {
				//登录成功，生成JWT token
				Admin admin = new Admin();
				admin.setAdminName(adminName);
				
				String token = jwtUtil.generateToken(admin);
				
				JSONObject adminData = new JSONObject();
				adminData.put("token", token);
				adminData.put("name", adminName);
				adminData.put("type", "admin");
				
				return Result.success(adminData);
			} else {
				return Result.error("密码错误");
			}
		}
		catch (Exception e) {
			return Result.error("登录失败" + e.getMessage());
		}
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	public Result<String> logout(HttpServletRequest  request){
		
		return Result.success("注销成功", null);
	}
}
